﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Grishko.Tools;
using OutdoorLib.BaseEntity.Constraction;
using Grishko.UI;
using OutdoorLib.BaseEntity.Dictionary;
using Grishko.DataTier;

public partial class ConstractionEditor : MasterPage_EditControl
{
    Func<ListViewDataItem, bool> LvUpdCmd = null;        
    private const string qSessionKey= "ConstractionEditor_Key";
    

    protected void Page_Load(object sender, EventArgs e)
    {
        MyInit();
        if (!IsPostBack)
                MyDataBind();
        
    }

    protected void MyInit()
    {
        //привязать событие открыть закрыть lvSideeditor
        if (lvSideList.EditItem != null)
        {
            Ctl_SideEditor r = (Ctl_SideEditor)lvSideList.EditItem.FindControl("crlSideEditor2");
            r.OnCancelClick = SIDE_OnCancelClick;
            r.OnSaveClick = SIDE_OnSaveClick;
            SetAlertForTextBox(r.Controls , "TextBox", "onChange", "ShowAlert()");
        }

        SetAlertForTextBox();
    }

    protected bool IsNewRecord
    { get { return GlobalConstants.IsNewRecord(CurrentID); } }
    
    private void MyDataBind()
    {
        
        lvConstractionType.DataSource = ConstractionAsCollection;
        lvAdresProgramm.DataSource = ConstractionAsCollection;
        lvCommonCondition.DataSource = ConstractionAsCollection;
        lvGeoBinding.DataSource = ConstractionAsCollection;
        lvTransportLocation.DataSource = ConstractionAsCollection;
        lvMapEditor.DataSource = ConstractionAsCollection;        
        lvSideList.DataSource = Constraction.SideList.ToList<Side>();

        DataBind();
    }

    #region DataSource
    private string CurrentID
    {
        get
        {            
            return Request.QueryString[GlobalConstants.qID];
        }

    }

    private string CurrentTagName
    {
        get { return Request.QueryString[GlobalConstants.qTagName]; }
    }

   
    ConstractionEntity _Constraction = null;
    protected virtual ConstractionEntity Constraction
    {
        get
        {
            if (null != _Constraction)
                        return _Constraction;


            if (GlobalConstants.IsNewRecord(CurrentID))
            {
                _Constraction = (ConstractionEntity)AppEnvironment.ObjectFactory.GetNewObject(CurrentTagName, GlobalConstants.GetNewID(CurrentID));
                AppEnvironment.BusinessRules.SetDefaultValue(_Constraction,null);
            }
            else
                _Constraction = (ConstractionEntity)AppEnvironment.ObjectFactory.GetObject(CurrentID, CurrentTagName);

            return _Constraction;
        }        
    }



    protected virtual List<ConstractionEntity> ConstractionAsCollection
    {
        get
        {
            List<ConstractionEntity> List = new List<ConstractionEntity>();
            List.Add(Constraction);
            return List;
        }
    }

    #endregion

    #region UpdateLv    
    
    private bool UpdatelvMapEditor(ListViewDataItem item)
    {
        Constraction.MapX = Convert .ToDouble (hfX.Value.Replace (".",","));
        Constraction.MapY = Convert.ToDouble(hfY.Value.Replace(".", ","));
        return true;
    }
    private bool UpdateAdresProgramm(ListViewDataItem item)
    {   
        TreeDictionaryControl_Rb tv;
        tv = (TreeDictionaryControl_Rb)lvAdresProgramm.EditItem.FindControl("tv_AdresProgramm");
        tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F_AdressProgramm();
        Constraction.AdressProgramm = tv.TreeDictionaryItemValue;
        return true;
    }    
    
    private bool UpdateConstractionType(ListViewDataItem item)
    {
        TreeDictionaryControl_Rb tv;
        tv = (TreeDictionaryControl_Rb)lvConstractionType.EditItem.FindControl("tv_ConstractionType");
        tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_ConstractionType); 
        Constraction.ConstractionType = tv.TreeDictionaryItemValue;
        return true;
    }

    private bool UpdateCommonCondition(ListViewDataItem item)
    {
        TreeDictionaryControl_Rb tv;
        tv = (TreeDictionaryControl_Rb)lvCommonCondition.EditItem.FindControl("tv_Condition");
        tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_RestrictionsOnPlacement ); 
        Constraction.RestrictionsOnPlacement = tv.TreeDictionaryItemValue;
        return true;
    }
    
    private bool UpdateGeoBinding(ListViewDataItem item)
    {
        TreeDictionaryControl_Rb tv;
        tv = (TreeDictionaryControl_Rb)lvGeoBinding.EditItem.FindControl("tv_GeoBinding");
        tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_GeoBinding  ); 
        Constraction.GeoBinding  = tv.TreeDictionaryItemValue;
        return true;
    }

    private bool UpdateTransportLocation(ListViewDataItem item)
    {
        TreeDictionaryControl_Rb tv;
        tv = (TreeDictionaryControl_Rb)lvTransportLocation.EditItem.FindControl("tv_Location");
        tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_LocationDescribe ); 
        Constraction.LocationDescribe = tv.TreeDictionaryItemValue;
        return true;
    }

    protected bool SIDE_OnCancelClick()
    {
        lvSideList.EditIndex = -1;
        lvSideList.DataSource = Constraction.SideList.ToList<Side>();
        lvSideList.DataBind();
        return true;
    }

    /// <summary>
    /// Сохранение дернутое стороной
    /// </summary>
    /// <returns></returns>
    protected bool SIDE_OnSaveClick()
    {
        if (!Save())
            return false;

        SIDE_OnCancelClick();
        HideAlert();
        return true;
    }

    
   
    
    #endregion 

    #region LvCommand
    /// <summary>
    /// Прорисовка карты
    /// </summary>
    
    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;
        ListView lv = (ListView)sender;
        switch (lv.ID)
        {
                            

            case "lvConstractionType":
                LvUpdCmd = UpdateConstractionType;
                break;
            case "lvAdresProgramm":
                LvUpdCmd = UpdateAdresProgramm;
                break;
            case "lvCommonCondition":
                LvUpdCmd = UpdateCommonCondition;
                break;
            case "lvGeoBinding":
                LvUpdCmd = UpdateGeoBinding;
                break;
            case "lvTransportLocation":
                LvUpdCmd = UpdateTransportLocation;
                break;
            case "lvMapEditor":
               LvUpdCmd = UpdatelvMapEditor;
                break;
        }

        switch (e.CommandName)
        {
            case "Edit":
                {
                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;
                    break;
                }
            case "Insert":
                {
                    break;
                }
            case "Update":
                {

                    // обновить поле
                    if (LvUpdCmd((ListViewDataItem)e.Item))
                    {
                        lv.EditIndex = -1;
                        // если бизнес правила в порядке -попытаться неявно сохраниться
                        if (AppEnvironment.BusinessRules.CheckUpdate(Constraction).Count == 0)
                        {
                            if (Save())
                                        break;
                            
                        }
                       // Если вышли из блока без сохранения - показать предупреждение  
                       ShowAlert();
                    }
                    break;
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                }
        }

        switch (lv.ID)
        {

            case "lvSideList":
                lv.DataSource = Constraction.SideList.ToList<Side>();
                break;
            default:
                lv.DataSource = ConstractionAsCollection; ;
                break;
        }
        lv.DataBind();
        //SetAlertForTextBox(this.Controls, "TextBox", "onChange", "ShowAlert()");
        //SetMsg_EditStatus();
    }
    protected virtual void ItemCanceling(object sender, ListViewCancelEventArgs e)
    {

    }
    protected virtual void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
    protected virtual void ItemDataBound(object sender, ListViewItemEventArgs e)
    {

    }    
    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {
        ListView lv = (ListView)sender;
        TreeDictionaryControl_Rb tv = null;
        TreeDictionaryItem source = null;
        switch (lv.ID)
        {
            case "lvConstractionType":
                source =  AppEnvironment.DictionarySource.GetTreeDictionaryItem(TreeDictionaryItem.TreeDictionary_ConstractionType); 
                tv = (TreeDictionaryControl_Rb)lvConstractionType.EditItem.FindControl("tv_ConstractionType");                
                tv.TreeDictionaryItemValue = (Constraction.ConstractionType == null ? source.BuildValue() : Constraction.ConstractionType);
                tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_ConstractionType); 
                tv.DataBind();
                break;
            case "lvAdresProgramm":                
                tv = (TreeDictionaryControl_Rb)lvAdresProgramm.EditItem.FindControl("tv_AdresProgramm");
                tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F_AdressProgramm();                
                tv.TreeDictionaryItemValue = Constraction.AdressProgramm;
                tv.DataBind();
                break;
            case "lvCommonCondition":
                source = AppEnvironment.DictionarySource.GetTreeDictionaryItem(TreeDictionaryItem.TreeDictionary_RestrictionsOnPlacement); 
                tv = (TreeDictionaryControl_Rb)lvCommonCondition.EditItem.FindControl("tv_Condition");                
                tv.TreeDictionaryItemValue = (Constraction.RestrictionsOnPlacement == null ? source.BuildValue() : Constraction.RestrictionsOnPlacement);
                tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_RestrictionsOnPlacement);
                tv.DataBind();
                break;
            case "lvGeoBinding":
                source = AppEnvironment.DictionarySource.GetTreeDictionaryItem(TreeDictionaryItem.TreeDictionary_GeoBinding ); 
                tv = (TreeDictionaryControl_Rb)lvGeoBinding.EditItem.FindControl("tv_GeoBinding");
                tv.TreeDictionaryItemValue = (Constraction.GeoBinding == null ? source.BuildValue() : Constraction.GeoBinding);
                tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_GeoBinding);
                tv.DataBind();
                break;
            case "lvTransportLocation":
                source = AppEnvironment.DictionarySource.GetTreeDictionaryItem(TreeDictionaryItem.TreeDictionary_LocationDescribe); 
                tv = (TreeDictionaryControl_Rb)lvTransportLocation.EditItem.FindControl("tv_Location");
                tv.TreeDictionaryItemValue = (Constraction.LocationDescribe == null ? source.BuildValue() : Constraction.LocationDescribe);
                tv.F_DataSource = AppEnvironment.DictionarySource.GetTreeDictionaryItem_F(TreeDictionaryItem.TreeDictionary_LocationDescribe);
                tv.DataBind();
                break;
            case "lvMapEditor":
                //EditPointScript
                //center_x,center_y,x,y,hfX_ID,hfY_ID
                string[] p={AppEnvironment .CurrentAgency.Settings .CentrMapX.ToString ().Replace (",","."),
                            AppEnvironment .CurrentAgency.Settings .CentrMapY .ToString ().Replace (",","."),
                            Constraction.MapX .ToString ().Replace (",","."),
                            Constraction.MapY .ToString ().Replace (",","."),
                            hfX .ClientID ,
                            hfY .ClientID 
                           } ;
                string f = "EditPointScript({0},{1},{2},{3},'{4}','{5}');";
                f = string.Format(f, p);
                ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(), f, true);

                break;
            
        }

    }
    #endregion

    #region Click
    protected void btnSaveExit_Click(object sender, EventArgs e)
    {
        
        QueryStringTools.RefreshPageWitchReturnUrl();
    }

    protected void btnAddSide_Click(object sender, EventArgs e)
    {
        //создать
        Side side = new Side() { SurfaceCount = 1 };
        //параметры по умолчанию
        object[] param = { Constraction };
        AppEnvironment.BusinessRules.SetDefaultValue(side,param);
        //добавить сторону
        Constraction.SideList.Add(side);

        MyDataBind();
        ShowAlert();

    }

    protected void ReadForm()
    {
        Constraction.Number = txtNumber.Text;
        Constraction.Street = txtStreets.Text;
        Constraction.Describe = txtDescribe.Text;

    }
    protected void btnSaveCommonInfo_Click(object sender, EventArgs e)
    {
        bool bRedirect = GlobalConstants.IsNewRecord(CurrentID);
        HideAlert();
        if (!Save())
                    return;

        if (bRedirect)
            QueryStringTools.RefreshPage(GlobalConstants.qID + "=" + CurrentID);
        
    }

    private bool Save()
    {        
        try
        {
            ReadForm();            
            // проверить бизнес правила на вставку/обновление                        
            List <string > CheckResult=AppEnvironment.BusinessRules.CheckUpdate(Constraction);
            if (0==CheckResult.Count )
            {
                AppEnvironment.ObjectFactory.SaveWitchChild(Constraction);
                return true;
            }
            else
            {
                AppEnvironment.Helper.RegistredStartUpAlert(this,CheckResult);
                return false;
            }

        }
        
        catch 
        {
            return false  ;
        }
        

    }

    #endregion

    protected void Button1_Click(object sender, EventArgs e)
    {
        int f = (Constraction.SideList[0] as Side).CurrentPrice;
    }
}
